package cn.minimelon.api.service.data.factory;

import cn.hutool.core.util.StrUtil;
import cn.minimelon.api.domain.module.vo.DataModelVO;
import cn.minimelon.api.exception.ServiceException;
import cn.minimelon.api.service.data.ModelDeployService;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ModelDeployConsumer implements TopicConsumer {
    private final ModelDeployService modelDeployService;

    public ModelDeployConsumer(ModelDeployService modelDeployService) {
        this.modelDeployService = modelDeployService;
    }

    @Override
    public void accept(String message) {
        // 建表与重建索引等
        log.info("ModelDeployConsumer >>> Received Message: {}", message);
        DataModelVO model = ONode.deserialize(message, DataModelVO.class);
        buildJsonInfo(model);
        if (model.getVersion() < 1) {
            try {
                modelDeployService.createDynamicsTable(model);
            } catch (Exception ex) {
                log.error("createDynamicsTable error", ex);
                throw new ServiceException("createDynamicsTable error");
            }
        } else {
            log.info("update model cache info");
            modelDeployService.removeModelCache(model);
        }
    }

    private void buildJsonInfo(DataModelVO res) {
        if (StrUtil.isNotEmpty(res.getExtJson())) {
            res.setExt(ONode.deserialize(res.getExtJson(), Map.class));
            res.setExtJson(null);
        } else {
            res.setExt(new HashMap<>());
        }
        if (StrUtil.isNotEmpty(res.getSwtJson())) {
            res.setSwt(ONode.deserialize(res.getSwtJson(), Map.class));
            res.setSwtJson(null);
        } else {
            res.setSwt(new HashMap<>());
        }
    }
}
